<template>
	<view class="viewport">
		<!-- 推荐封面图 -->
		<view class="cover">
			<image
				src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-05-20/84abb5b1-8344-49ae-afc1-9cb932f3d593.jpg">
			</image>
		</view>
		<!-- 推荐选项 -->
		<view class="tabs">
			<text class="text" v-for="(v,index) in tabs" :class="{active: index === activeIndex}"
				@tap="activeIndex = index">{{v.name}}</text>
		</view>
		<!-- 推荐列表 -->
		<scroll-view v-for="(item,index) in tabs" :key="item.id" scroll-y enable-back-to-top refresher-enabled
			class="scroll-view" v-show="activeIndex === index" @scrolltolower="onScrolltolower">
			<!-- <view class="goods">
				<navigator hover-class="none" class="navigator" v-for="goods in goodses" :key="goods.id"
					:url="`/pages/goods/goods?id=${goods.id}`">
					<image class="thumb" :src="getFirstImageUrl(goods.imgUrl)">
					</image>
					<view class="name ellipsis">{{goods.name}}</view>
					<view class="price">
						<text class="symbol">¥</text>
						<text class="number">{{goods.price}}</text>
					</view>
				</navigator>
			</view> -->
			<view class="goods">  
			    <navigator hover-class="none" class="navigator" v-for="goods in goodses" :key="goods.id" :url="goods.isAd ? '' : `/pages/goods/goods?id=${goods.id}`">  
			        <view v-if="goods.isAd" class="ad-container">  
			            <!-- 广告内容 -->  
			            <image class="ad-thumb" :src="goods.imgUrl"></image>  
			            <!-- 其他广告信息 -->  
						<view>这是一条广告</view>
			        </view>  
			        <view v-else>  
			            <image class="thumb" :src="getFirstImageUrl(goods.imgUrl)"></image>  
			            <view class="name ellipsis">{{goods.name}}</view>  
			            <view class="price">  
			                <text class="symbol">¥</text>  
			                <text class="number">{{goods.price}}</text>  
							<text class="buy">{{goods.sale}}人购买</text>
			            </view>  
			        </view>  
			    </navigator>  
			</view>
			<view class="loading-text">{{finish?'我已到底了':'正在加载...'}}</view>
		</scroll-view>
	</view>
</template>
<script setup lang="ts">  
import { onLoad } from '@dcloudio/uni-app';  
import { ref, reactive, toRefs, watch } from 'vue';  
import { getGoodsApi } from "@/api/goods/index.ts";  
import type { GoodsVo } from '@/api/goods/types.ts';  
  
const activeIndex = ref(0);  
const finish = ref(false); // 下拉刷新结束标记  
  
const tabs = ref([  
    { id: 0, name: '新品推荐', orderSort: 'new' },  
    { id: 1, name: '热销商品', orderSort: 'hot' }  
]);  
  
const goodses = ref<GoodsVo[]>([]);  
  
const data = reactive<any>({  
    queryParams: {  
        pageNum: 1,  
        pageSize: 10,  
        orderSort: tabs.value[0].orderSort  // 初始化为第一个tab的orderSort  
    }  
});  
  
const { queryParams } = toRefs(data);  
/* 随机广告 */
const ad = {  
    id: 'ad_id',  
    name: '广告标题',  
    imgUrl: "http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-05-20/84abb5b1-8344-49ae-afc1-9cb932f3d593.jpg",  
    price: '欢迎来到广告区',  
    isAd: true // 标记这是一个广告对象  
};
/* 随机插入广告 */
  const insertAd = (goodsList: GoodsVo[], ad: any, adFrequency: number = 5) => {  
      const newList = [...goodsList];  
      for (let i = adFrequency; i < newList.length; i += adFrequency + Math.floor(Math.random() * adFrequency)) {  
          newList.splice(i, 0, ad); // 在随机位置插入广告  
      }  
      return newList;  
  }; 
  //TODO 在获取商品列表后调用insertAd函数,这个功能需要后台支持，暂偏

const getHotGoods = async () => {  
    if (finish.value === true) {  
        return;  
    }  
    const res = await getGoodsApi(queryParams.value);  
	const goodsWithAd = insertAd(res.rows, ad);  
    goodses.value = [...goodses.value, ...goodsWithAd]; // 使用扩展运算符合并数组  
    if (res.rows.length === 0) {  
        finish.value = true;  
    }  
};  
  
watch(activeIndex, (newIndex) => {  
    queryParams.value.orderSort = tabs.value[newIndex].orderSort;  
    queryParams.value.pageNum = 1; // 重置页码为1  
    goodses.value = []; // 清空当前商品列表  
    finish.value = false; // 重置finish状态  
    getHotGoods(); // 重新获取数据  
});  
/*取第一张图片*/
	const getFirstImageUrl = (imageUrls : string) => {
		const image = imageUrls.split(',')
		return image.length > 0 ? image[0] : '';
	}
/* 触底事件 */
const onScrolltolower = () => {  
    if (finish.value) return;  
    queryParams.value.pageNum++;  
    getHotGoods();  
};  
  
onLoad(() => {  
    getHotGoods();  
});  
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
		background-color: #f4f4f4;
		// overflow: hidden;
	}

	.viewport {
		display: flex;
		flex-direction: column;
		height: 100%;
		padding: 180rpx 0 0;
		position: relative;
	}

	.cover {
		width: 750rpx;
		height: 225rpx;
		border-radius: 0 0 40rpx 40rpx;
		overflow: hidden;
		position: absolute;
		left: 0;
		top: 0;
	}

	.scroll-view {
		flex: 1;
		overflow: hidden;

	}

	.tabs {
		display: flex;
		justify-content: space-evenly;
		height: 100rpx;
		line-height: 90rpx;
		margin: 0 20rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
		box-shadow: 0 4rpx 5rpx rgba(200, 200, 200, 0.3);
		color: #333;
		background-color: #fff;
		position: relative;
		z-index: 9;

		.text {
			margin: 0 20rpx;
			position: relative;
		}

		.active {
			&::after {
				content: '';
				width: 40rpx;
				height: 4rpx;
				transform: translate(-50%);
				background-color: #27ba9b;
				position: absolute;
				left: 50%;
				bottom: 24rpx;
			}
		}
	}

	.goods {
		column-count: 2;//指定列表
		column-gap: 20rpx; //列间距
		padding: 20rpx 20rpx;

		.navigator {
			break-inside: avoid; // 防止项目被分割到两列
			width: 100%; // 宽度设置为100%，实际宽度会由列宽决定  
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			overflow: hidden;
			background-color: #fff;
			box-sizing: border-box; // 防止内边距和边框破坏布局  
		}

		.thumb {
			width: 345rpx;
			height: 345rpx;
			object-fit: cover; //保持图片比例
		}
		.ad-container {  
		    display: flex;  
		    flex-wrap: wrap;  
		    justify-content: space-between;  
		    padding: 10px;  
		    background-color: #f4f4f4;  
		    border: 1px solid #ddd;  
		}  
		.ad-thumb {
			width: 345rpx;
			// height: 305rpx;
			object-fit: cover; //保持图片比例
		}

		.name {
			padding: 0 20rpx;
			height: 35rpx;
			margin: 10rpx 0;
			font-size: 26rpx;
			color: #262626;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 1;
			-webkit-box-orient: vertical;
		}

		.price {
			padding: 0 20rpx 20rpx;
			line-height: 1;
			padding-top: 4rpx;
			color: #cf4444;
			font-size: 26rpx;
		}

		.symbol {
			font-size: 70%;
		}

		.decimal {
			font-size: 70%;
		}
		.buy {
			padding-left: 20rpx;
			font-size: 22rpx;
			color: #262626;
		}
	}

	.loading-text {
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx 0 50rpx;
	}
</style>